#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能诊断工作流
结合 AI 和 prompts 进行自动化代码分析和错误诊断
"""
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any

from ai_client import AIClientFactory, AIProvider
from prompt_loader import PromptLoader
from structured_logger import StructuredLogger


class SmartDiagnosticWorkflow:
    """智能诊断工作流"""

    def __init__(self, provider: AIProvider = AIProvider.MOCK, output_dir: str = "reports"):
        """
        初始化工作流

        Args:
            provider: AI 提供商
            output_dir: 报告输出目录
        """
        self.ai_client = AIClientFactory.create(provider)
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)
        self.prompt_loader = PromptLoader()
        self.structured_logger = StructuredLogger(output_dir)

    def load_error_log(self, log_file: str = "reports/last_error.log") -> str:
        """加载错误日志"""
        log_path = Path(log_file)

        if not log_path.exists():
            return "未找到错误日志"

        with open(log_path, "r", encoding="utf-8") as f:
            return f.read()

    def analyze_errors(self, error_log: str) -> dict[str, Any]:
        """
        使用 AI 分析错误日志

        Args:
            error_log: 错误日志内容

        Returns:
            分析结果
        """
        print("[SmartDiagnose] 加载 AI 诊断 prompt...")

        # 加载诊断 prompt
        try:
            prompt_template = self.prompt_loader.build_system_prompt("ai_auto_self_diagnose")
        except (ValueError, FileNotFoundError) as e:
            print(f"[SmartDiagnose] 未找到 prompt，使用默认: {e}")
            prompt_template = "你是错误诊断专家，请分析以下错误日志并给出修复建议。"

        # 构建消息
        messages = [
            {"role": "system", "content": prompt_template},
            {
                "role": "user",
                "content": f"请分析以下错误日志并输出 JSON 格式的诊断报告:\n\n{error_log}",
            },
        ]

        print("[SmartDiagnose] 正在分析错误...")

        try:
            response = self.ai_client.chat(messages, temperature=0.3)

            # 尝试解析 JSON
            try:
                # 提取 JSON 块（如果响应包含其他内容）
                if "```json" in response:
                    json_start = response.find("```json") + 7
                    json_end = response.find("```", json_start)
                    response = response[json_start:json_end].strip()
                elif "```" in response:
                    json_start = response.find("```") + 3
                    json_end = response.find("```", json_start)
                    response = response[json_start:json_end].strip()

                result = json.loads(response)
            except json.JSONDecodeError:
                result = {"raw_response": response, "parsed": False, "error": "Failed to parse JSON"}

            return result

        except Exception as e:
            return {"error": str(e), "success": False}

    def check_code_quality(self, file_path: str) -> dict[str, Any]:
        """
        检查代码质量

        Args:
            file_path: 代码文件路径

        Returns:
            质量检查结果
        """
        print(f"[SmartDiagnose] 检查代码质量: {file_path}")

        # 读取代码
        code_path = Path(file_path)
        if not code_path.exists():
            return {"error": f"File not found: {file_path}"}

        with open(code_path, "r", encoding="utf-8") as f:
            code = f.read()

        # 加载质量检查 prompt
        try:
            prompt = self.prompt_loader.build_system_prompt("ai_quality_guard")
        except (ValueError, FileNotFoundError) as e:
            print(f"[SmartDiagnose] 未找到 prompt，使用默认: {e}")
            prompt = "你是代码质量检查专家，请检查代码并给出改进建议。"

        # 分析代码
        result = self.ai_client.analyze_code(code, prompt)
        result["file"] = file_path

        return result

    def generate_diagnostic_report(self, analysis_result: dict[str, Any]) -> Path:
        """
        生成诊断报告

        Args:
            analysis_result: 分析结果

        Returns:
            报告文件路径
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        report_file = self.output_dir / f"ai_diagnostic_{timestamp}.json"

        # 添加元数据（包含 prompt 版本）
        prompt_info = {}
        try:
            prompt_data = self.prompt_loader.load_prompt("ai_auto_self_diagnose")
            prompt_info = {
                "prompt_id": prompt_data["id"],
                "prompt_version": prompt_data["version"],
                "prompt_file": prompt_data["file"],
                "prompt_checksum": prompt_data["checksum"]
            }
        except Exception:
            pass

        report = {
            "timestamp": datetime.now().isoformat(),
            "version": "1.0",
            "prompt_info": prompt_info,
            "analysis": analysis_result,
        }

        # 保存 JSON 报告
        with open(report_file, "w", encoding="utf-8") as f:
            json.dump(report, f, indent=2, ensure_ascii=False)

        print(f"📄 诊断报告已生成: {report_file}")

        # 同时生成 Markdown 报告
        md_file = report_file.with_suffix(".md")
        self._generate_markdown_report(report, md_file)

        return report_file

    def _generate_markdown_report(self, report: dict[str, Any], output_file: Path) -> None:
        """生成 Markdown 格式的报告"""
        analysis = report.get("analysis", {})

        with open(output_file, "w", encoding="utf-8") as f:
            f.write("# 🤖 AI 诊断报告\n\n")
            f.write(f"**生成时间**: {report['timestamp']}\n\n")

            # 摘要
            if "summary" in analysis:
                f.write("## 📋 摘要\n\n")
                f.write(f"{analysis['summary']}\n\n")

            # 根因分析
            if "root_cause_analysis" in analysis:
                f.write("## 🔍 根因分析\n\n")
                for item in analysis["root_cause_analysis"]:
                    f.write(f"### {item.get('category', 'Unknown')}\n\n")
                    f.write(f"{item.get('description', '')}\n\n")
                    f.write(f"**证据**: {item.get('evidence', 'N/A')}\n\n")
                    f.write(f"**置信度**: {item.get('confidence', 0):.2%}\n\n")

            # 幻觉检测
            if "hallucination_detection" in analysis:
                f.write("## 🚨 幻觉检测\n\n")
                hd = analysis["hallucination_detection"]
                f.write(f"**幻觉标记**: {'是' if hd.get('hallucination_flag') else '否'}\n")
                f.write(f"**风险等级**: {hd.get('risk_level', 'N/A')}\n\n")

            # 建议操作
            if "recommended_actions" in analysis:
                f.write("## 💡 建议操作\n\n")
                for action in analysis["recommended_actions"]:
                    f.write(f"- {action}\n")
                f.write("\n")

            # 原始响应（如果解析失败）
            if analysis.get("parsed") is False:
                f.write("## 📝 原始响应\n\n")
                f.write("```\n")
                f.write(analysis.get("raw_response", ""))
                f.write("\n```\n")

        print(f"📄 Markdown 报告已生成: {output_file}")

    def run_full_diagnostic(self) -> dict[str, Any]:
        """
        运行完整诊断流程

        Returns:
            诊断结果
        """
        print("\n" + "=" * 60)
        print("🚀 启动完整诊断流程")
        print("=" * 60 + "\n")

        # 1. 加载错误日志
        print("1️⃣ 加载错误日志...")
        error_log = self.load_error_log()

        if error_log == "未找到错误日志":
            print("✅ 未发现错误日志，系统正常")
            return {"status": "healthy", "message": "No errors detected"}

        # 2. 分析错误
        print("\n2️⃣ 分析错误...")
        analysis = self.analyze_errors(error_log)

        # 3. 生成报告
        print("\n3️⃣ 生成诊断报告...")
        report_file = self.generate_diagnostic_report(analysis)

        # 4. 输出结果
        print("\n" + "=" * 60)
        print("✅ 诊断完成")
        print("=" * 60)
        print(f"报告位置: {report_file}")

        return {
            "status": "completed",
            "report_file": str(report_file),
            "analysis": analysis,
        }


def main() -> int:
    """主函数"""
    import argparse

    parser = argparse.ArgumentParser(description="智能诊断工作流")
    parser.add_argument(
        "--provider",
        choices=["openai", "anthropic", "mock"],
        default="mock",
        help="AI 提供商",
    )
    parser.add_argument(
        "--check-file",
        type=str,
        help="检查指定文件的代码质量",
    )

    args = parser.parse_args()

    # 选择 AI 提供商
    provider_map = {
        "openai": AIProvider.OPENAI,
        "anthropic": AIProvider.ANTHROPIC,
        "mock": AIProvider.MOCK,
    }
    provider = provider_map[args.provider]

    # 创建工作流
    workflow = SmartDiagnosticWorkflow(provider=provider)

    # 如果指定了文件，检查代码质量
    if args.check_file:
        result = workflow.check_code_quality(args.check_file)
        print("\n📊 代码质量检查结果:")
        print(json.dumps(result, indent=2, ensure_ascii=False))
        return 0

    # 否则运行完整诊断
    result = workflow.run_full_diagnostic()

    if result["status"] == "healthy":
        return 0
    elif result["status"] == "completed":
        return 0
    else:
        return 1


if __name__ == "__main__":
    sys.exit(main())
